package com.example.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.domain.Roll;
import com.example.service.RollService;
import com.example.service.UserService;
import com.example.util.api.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/roll")
public class RollController {

    @Autowired
    private RollService service;

    @Autowired
    private UserService userService;

    @GetMapping("/list")
    public R list(Roll roll) {
        LambdaQueryWrapper<Roll> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(roll.getCouponCode()), Roll::getCouponCode, roll.getCouponCode());
        List<Roll> list = service.list(wrapper);
        return R.data(list);
    }

    @DeleteMapping("/delete")
    public R delete(@RequestParam("couponCode") String couponCode) {
        service.removeById(couponCode);
        return R.success("操作成功");
    }

    @PostMapping("/save")
    public R save(@RequestBody Roll roll) {
        Roll exist = service.getById(roll.getCouponId());
        if (exist != null) {
            return R.fail("优惠价ID重复");
        }

        LambdaQueryWrapper<Roll> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Roll::getCouponCode, roll.getCouponCode());
        if (service.count(wrapper) > 0) {
            return R.fail("优惠价编号重复");
        }

        if (userService.getById(roll.getSno()) == null) {
            return R.fail("学号不存在");
        }
        roll.setUsed(0);
        roll.setExpiryDate(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24));
        service.save(roll);
        return R.success("操作成功");
    }
    @PutMapping("/update")
    public R update(@RequestBody Roll roll) {
        // 先验证要更新的优惠券编号对应的优惠券是否存在
        LambdaQueryWrapper<Roll> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Roll::getCouponCode, roll.getCouponCode());
        if (service.count(wrapper) == 0) {
            return R.fail("要更新的优惠券不存在");
        }



        boolean result = service.updateRoll(roll);
        if (result) {
            return R.success("优惠券更新操作成功");
        }
        return R.fail("优惠券更新操作失败");
    }
}
